package com.triptogether.utils.gcm;

import java.util.HashMap;
import java.util.Map;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.triptogether.utils.gcm.commands.GcmChatCommand;
import com.triptogether.utils.log.Logger;

/**
 * This {@code IntentService} does the actual handling of the GCM message.
 * {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
 * partial wake lock for this service while the service does its work. When the
 * service is finished, it calls {@code completeWakefulIntent()} to release the
 * wake lock.
 */
public class GcmIntentService extends IntentService {

	public final String TAG = Logger.makeLogTag(this.getClass());
	private static Map<String, GcmCommand> commandsMap;
	static {
		// Init the Map of the commands to use
		commandsMap = new HashMap<String, GcmCommand>();
		commandsMap.put(GcmCons.CHAT_COMMAND_MAP_KEY, new GcmChatCommand());
	}

	public GcmIntentService() {
		super(GcmIntentService.class.getName());
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Bundle extras = intent.getExtras();
		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
		
		// The getMessageType() intent parameter must be the intent you received
		// in your BroadcastReceiver.
		String messageType = gcm.getMessageType(intent);

		if (!extras.isEmpty()) { // has effect of unparcelling Bundle
			/*
			 * Filter messages based on message type.
			 * Since it is likely that GCM will be extended in the future with new message types, 
			 * just ignore any message types you're not interested in, or that you don't recognize.
			 */
			if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
				Logger.LOGW(TAG, "send error: " + extras.toString());
			} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
				Logger.LOGW(TAG, "Deleted messages on server: " + extras.toString());
				// If it's a regular GCM message, do some work.
			} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
				String commandName = extras.getString(GcmCons.EXTRA_KEY_COMMAND_TO_EXECUTE);
				if(commandName != null) {
    				GcmCommand commandToExecute = commandsMap.get(commandName);
    				if (commandToExecute != null) {
        				commandToExecute.execute(this, extras);
    				}
    				else {
    					Logger.LOGE(TAG, "there is no command with the name: " + commandName + " in the commands map");
    				}
				} else {
					Logger.LOGE(TAG, "no '" + GcmCons.EXTRA_KEY_COMMAND_TO_EXECUTE + "' was sent with the message");
				}
			}
		}
		
		// Release the wake lock provided by the WakefulBroadcastReceiver.
		GcmBroadcastReceiver.completeWakefulIntent(intent);
	}
}